var TestPage = new (function() {
	this.modelDownloadTorrent 	= ElementHTML(".download-block.model-torrent");
	this.modelDownloadHTTP 		= ElementHTML(".download-block.model-http");
	
	var downloadBlocksUI = [];
	var lastDownloadList = [];
	
	var Tools = ToolsPrototypeJS;
	var $this = this;
	var interval;
	
	function onGetDownloadList(data, resp) {
		var downloadlist = resp.result;
		
		var downloadsRunning = downloadlist.getDownloads({downloading: true});
		console.log(downloadsRunning);
		var idsRunning = [];
		// Rafraichissement des téléchargement en cours
		for (var i = 0; i < downloadsRunning.length; i++) {
			var download = downloadsRunning[i];
			var ui = getDownloadUI(download);
			ui.setFillingObject(download);
			idsRunning.push(download.id);
			console.log(download);
		}
		
		// Suppression des téléchargement terminés
		for (var i = 0; i < lastDownloadList.length; i++) {
			var id = lastDownloadList[i].id;
			if (idsRunning.indexOf(id) == null) {
				var ui = downloadBlocksUI[id];
				var elem = ui.getElement();
				elem.parentNode.removeChild(elem);
				unset(downloadBlocksUI[id]);
			}
		}
		lastDownloadList = downloadsRunning;
	}
	
	function getDownloadUI(o) {
		var ui = null;
		if (downloadBlocksUI[o.id] != undefined) {
			ui = downloadBlocksUI[o.id];
		}
		else {
			ui = createDownloadUI(o);
		}
		return ui;
	}
	
	function createDownloadUI(o) {
		
		var elem;
		if (o.type == "torrent") {
			elem = $this.modelDownloadTorrent.cloneNode(true);
			Tools.removeClassName(ui, "model-torrent");
		}
		else {
			elem = $this.modelDownloadHTTP.cloneNode(true);
			Tools.removeClassName(ui, "model-http");
		}
		Tools.$first("body").appendChild(elem);
		var ui = new FreeboxLinkDownloadUI(elem);
		ui.setFillingObject(o);
		downloadBlocksUI[o.id] = ui;
		Tools.removeClassName(elem, "hidden");
		return ui;
	}
	
	function askDownloadList() {
		var api = FreeboxLinkAPI.get();
		api.getSeedboxDownloadList(onGetDownloadList);
	}
	
	this.documentready = function() {
		var api = FreeboxLinkAPI.get();
		api.connect();
		setInterval(askDownloadList, 300);
	};
});
DocumentHTML.load(TestPage);